﻿using System.Collections.Generic;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Entities.Common;
using Jayden.Dll.Web.Controls.Edit;
using Jayden.Dll.Web.Helper;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.HtmlControls.Generics;
using Jayden.Dll.Web.Json;

namespace Jayden.Dll.Web.Controls
{
	public class PostArticle : Article
	{
		private H1 m_Title;
		private Div m_Content;
		private Span m_Author;
		private Time m_Time;

		private Ul m_Actions;
		private A m_Edit;
		private A m_Delete;

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);

			m_Actions = GetElementByServerId<Ul>("actions");
			m_Edit = GetElementByServerId<A>("edit");
			m_Delete = GetElementByServerId<A>("delete");

			m_Title = GetElementByServerId<H1>("title");
			m_Content = GetElementByServerId<Div>("content");
			m_Author = GetElementByServerId<Span>("author");
			m_Time = GetElementByServerId<Time>("time");
		}

		public void LoadPost(Post post, HtmlControlLoader loader = null)
		{
			Lang = post.CultureCode;
			if (m_Edit != null)
				m_Edit.HRef = "?editPostId=" + post.PostId;
			if (m_Delete != null)
				m_Delete.HRef = "?deletePostId=" + post.PostId;
			m_Title.InnerText = post.Title;
			m_Content.Clear();
			m_Content.AddHtml(post.Body, loader);
			m_Author.InnerText = post.Author;
			m_Time.DateTime = HtmlHelper.ToHtmlDateTime(post.DateTime);
			m_Time.InnerText = post.DateTime.ToString(@"dddd, d MMMM yyyy \a\t H\:mm");
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			m_Edit.ServerRender = (context.User != null && context.User.RoleNames.Contains("editor"));
			m_Delete.ServerRender = (context.User != null && context.User.RoleNames.Contains("admin"));

			m_Actions.ServerRender = (m_Edit.ServerRender || m_Delete.ServerRender);
			base.ProcessHtmlRequest(context);
		}
	}
	public class PostsSection : Section
	{
		private Ol m_List;

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);

			m_List = GetElementByServerId<Ol>("list", true);
		}

		private void LoadFromContext(HttpHandlerContext context)
		{
			bool command = false;
			PostDataAccess postDataAccess = context.UnitOfWork.DataAccessManager.GetDataAccess<PostDataAccess, Post>();
			if (postDataAccess != null)
			{
				if (context.User != null && context.User.RoleNames.Contains("admin"))
				{
					string postIdStr = context.Request["deletePostId"];
					long postId = 0;
					if (postIdStr != null)
						long.TryParse(postIdStr, out postId);
					if (postId != 0)
					{
						ObjectId oid = context.UnitOfWork.NewObjectId(postDataAccess.Entity, postId);
						postDataAccess.Delete(oid);
						command = true;
					}
				}
				PostArticle listElement = HtmlControl.LoadControl(context.Context.Server.MapPath(m_List.GetServerAttribute("item", "/Controls/PostArticle.xml")), context.ControlLoader) as PostArticle;
				if (listElement != null)
				{
					int count;
					List<Post> posts = postDataAccess.ReadByCategory(null, 0, int.MaxValue, out count);
					foreach (Post post in posts)
					{
						Li li = m_List.AddLi();
						// should create from a clone, it would be faster
						if (listElement == null)
							listElement = HtmlControl.LoadControl(context.Context.Server.MapPath(m_List.GetServerAttribute("item", "/Controls/PostArticle.xml")), context.ControlLoader) as PostArticle;
						listElement.LoadPost(post);
						li.AddControl(listElement);
						listElement = null;
					}
				}
			}
			if (command && context.Json != null)
			{
				JsonObject list = new JsonObject();
				list.Add("html", m_List.ToInnerHtml(context.Translator));
				context.Json.Add(m_List.Id, list);
			}
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			PostForm.PostCommandHandler handler = context.HandlerManager.GetHandler<PostForm.PostCommandHandler>();
			handler.PostSuccess += new PostForm.OnPostSuccess(PostSuccess);
			LoadFromContext(context);
			base.ProcessHtmlRequest(context);
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			PostForm.PostCommandHandler handler = context.HandlerManager.GetHandler<PostForm.PostCommandHandler>();
			handler.PostSuccess += new PostForm.OnPostSuccess(PostSuccess);
			LoadFromContext(context);
			base.ProcessJsonRequest(context);
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);
			string id = m_List.Id;
			context.Js[id].AppendAjaxHtmlHandler(m_List, false, false);
			context.Js[id].AppendOnInit(@"$('#" + id + @"').on('click', 'a[data-ajax=""true""]', JAYDEN.sfn.clickAjax);");
		}

		void PostSuccess(HttpHandlerContext context, Post user)
		{
			m_List.Clear();
			LoadFromContext(context);
			if (context.Json != null)
			{
				JsonObject list = new JsonObject();
				list.Add("html", m_List.ToInnerHtml(context.Translator));
				context.Json.Add(m_List.Id, list);
			}
		}
	}
}
